package com.yeswater.multithread.chapter2.test2_3.test2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * author : yeswater
 * date : 2023/10/20
 */

public class Run {
    public static void main(String[] args) throws InterruptedException {
        MyService service = new MyService();

        MyThread[] arr = new MyThread[5];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new MyThread(service);
        }
        for (int i = 0; i < arr.length; i++) {
            arr[i].start();
        }
        TimeUnit.SECONDS.sleep(1);
        System.out.println(MyService.atomicLong.get());
    }

    private static class MyThread extends Thread{
        private final MyService myService;

        public MyThread(MyService myService) {
            this.myService = myService;
        }

        @Override
        public void run() {
            myService.addNum();
        }
    }

    private static class MyService {
        public static AtomicLong atomicLong = new AtomicLong();


        synchronized public void addNum() {
            System.out.println(Thread.currentThread().getName() + " 加了 100 之后的值是:" + atomicLong.addAndGet(100));
            atomicLong.addAndGet(1);
        }
    }
}
